<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from "vue";
import { useExaminationStore } from "@/stores/examination";
import { useRouter } from "vue-router";
import { useStore } from "@/stores/index";

// import {
//   levelListApi,
//   subjectApi,
// } from "@/http/mockApi/students/examinationApi";
import { subjectAndLevelApi } from "@/http/Api/students/examinationApi";
import { ElMessageBox, ElMessage } from "element-plus";

const router = useRouter();
const examinationStore = useExaminationStore();
const userStore = useStore();

// 学科方向
const subject = reactive([
  {
    value: 0,
    text: "JAVA",
    itemsTitle: [],
  },
  {
    value: 1,
    text: "web前端",
    itemsTitle: [],
  },

  {
    value: 2,
    text: "测试",
    itemsTitle: [],
  },
  {
    value: 3,
    text: "安全",
    itemsTitle: [],
  },
  {
    value: 4,
    text: "嵌入式",
    itemsTitle: [],
  },
  {
    value: 5,
    text: "UI",
    itemsTitle: [],
  },
]);
const currentSubjectId = ref(-1); // watch 会改值，否则第一次不会触发，java 默认是 0

// 考试难度
interface LevelProps {
  text: string;
  value: string;
  startLevel: number;
  endLevel: number;
}
const levelTab = reactive<LevelProps[]>([]);
const currentLevel = ref(); // 当前难度

// level 集合
const levelArrayId = ref<number[]>([]);
const levelList = computed(() => {
  // 根据level范围生成level长度
  const arr = [];
  // console.log("计算当前level -- ", currentLevel.value);
  for (
    let i = currentLevel.value?.startLevel;
    i <= currentLevel.value?.endLevel;
    i++
  ) {
    arr.push(i);
  }
  return arr;
});

// 全选
const onAllChecked = () => {
  const arr = [...levelArrayId.value, ...levelList.value];
  // console.log([...new Set(arr)]);
  levelArrayId.value = [...new Set(arr)]; // 去重
};

const getArrDiff = (arr1: Array<any>, arr2: Array<any>) => {
  return arr1.concat(arr2).filter((v, i, arr) => {
    return arr.indexOf(v) === arr.lastIndexOf(v);
  });
};
// 反选
const onInvertChecked = () => {
  const diff = getArrDiff(levelArrayId.value, levelList.value);
  // console.log(diff);
  levelArrayId.value = diff;
};

// 考题数量
const examCountList = reactive([30, 50, 100]);
const examCount = ref(30);

// 考试类型编号
const examinationFrequency = reactive([
  {
    name: "日考",
    value: 1,
  },
  {
    name: "周考",
    value: 2,
  },
  {
    name: "月考",
    value: 3,
  },
]);
const examTypeId = ref(1);

onMounted(() => {
  // 学科及难度联动数据
  subjectAndLevelApi().then((res) => {
    // console.log("获取学科方向", res.data);
    subject.splice(0, subject.length, ...res.data.data);
    currentSubjectId.value = subject[0].value; // 默认选中学科
  });
});

// 方向改变自动切换难度
watch(currentSubjectId, () => {
  const currentL = subject.find((item) => item.value == currentSubjectId.value);
  levelTab.splice(0, levelTab.length, ...currentL!.itemsTitle);
  currentLevel.value = currentL!.itemsTitle[0];
});

// 提交试卷生成
const startExaminationHandler = () => {
  ElMessageBox.confirm("确认生成试卷吗？", {
    confirmButtonText: "确认生成",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      examinationStore
        .createExaminationAction({
          levelArrayId: levelArrayId.value,
          stuId: Number(userStore.user.userId),
          subjectId: Number(currentSubjectId.value),
          examCount: examCount.value,
          examTypeId: examTypeId.value,
        })
        .then(() => {
          router.push("/answertheexamination");
        })
        .catch((err) => {
          console.log("生成考题失败：", err);
          ElMessage.error(err);
        });
    })
    .catch(() => {
      console.log("取消生成");
    });
};
</script>

<template>
  <main>
    <div class="page-header">
      <div class="page-title">
        <p>生成试卷</p>
      </div>
    </div>

    <div class="page-body">
      <div class="create-group">
        <div class="create-group-title">学科方向：</div>
        <div class="subject-list">
          <div
            class="subject-list-item"
            :class="{ active: currentSubjectId == item.value }"
            v-for="item in subject"
            :key="item.value"
            @click="currentSubjectId = item.value"
          >
            {{ item.text }}
          </div>
        </div>
      </div>

      <div class="create-group">
        <div class="create-group-title">考题难度：</div>
        <div class="create-group-body">
          <div class="subject-list">
            <div
              class="subject-list-item"
              :class="{ active: currentLevel.value == Number(item.value) }"
              v-for="item in levelTab"
              :key="item.value"
              @click="currentLevel = item"
            >
              {{ item.text }}
            </div>
          </div>

          <div class="level-tab-body">
            <div class="level-all">
              <el-button
                size="small"
                class="el-checkbox-button--small"
                @click="onAllChecked"
                >全选</el-button
              >
              <el-button size="small" @click="onInvertChecked">反选</el-button>
            </div>
            <el-checkbox-group v-model="levelArrayId">
              <el-checkbox
                class="check-level"
                :label="item"
                v-for="item in levelList"
                :key="item.value"
              >
                <template #default>level {{ item }}</template>
              </el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </div>

      <div class="create-group">
        <div class="create-group-title">考题数量：</div>
        <div class="create-group-body">
          <el-select
            v-model="examCount"
            class="examination-count"
            placeholder="Select"
            size="small"
            style="width: 70px"
          >
            <el-option
              v-for="(item, index) in examCountList"
              :key="index"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
      </div>

      <div class="create-group">
        <div class="create-group-title">考试频率：</div>
        <div class="subject-list">
          <div
            class="subject-list-item"
            :class="{ active: examTypeId == item.value }"
            v-for="(item, index) in examinationFrequency"
            :key="index"
            @click="examTypeId = item.value"
          >
            {{ item.name }}
          </div>
        </div>
      </div>

      <div class="create-btn">
        <el-button
          @click="startExaminationHandler"
          class="beigin-btn"
          style="width: 200px"
          >开始考试</el-button
        >
      </div>
    </div>
  </main>
</template>

<style lang="scss">
@import "../../../assets/scss/global.scss";

.create-group {
  display: flex;
  padding: 20px 0;

  &:first-child {
    padding-top: 0;
  }

  .create-group-title {
    width: 100px;
    text-align: right;
  }

  .create-group-body {
    flex: 1;
  }
}

.subject-list {
  display: flex;

  .subject-list-item {
    padding: 0 10px;
    margin: 0 10px;
    height: 20px;
    user-select: none;
    cursor: default;
  }

  .active {
    background-color: $color-theme;
    color: #fff;
    border-radius: 20px;
  }
}
.level-all {
  padding: 20px 0;
}
.check-level {
  width: 77px;
}

.create-btn {
  text-align: center;
}

.beigin-btn {
  background-color: $color-theme;
  color: #fff;
}
</style>
